﻿using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace EnhancedCQWP
{
    public class SiteSelectionEditorPart : EditorPart
    {
        public SiteSelectionEditorPart(string webPartID)
        {
            ID = "SiteSelectionEditorPart" + webPartID;
            Title = "Sites";
        }

        private CheckBoxList _sitesCheckBoxList;
        private List<string> _selectedSites;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            _sitesCheckBoxList = BuildSiteList();
            Controls.Add(_sitesCheckBoxList);
        }

        CheckBoxList BuildSiteList()
        {
            var sites = new CheckBoxList();


            var currentSite = SPContext.Current.Web;
            SPWebCollection webcollection = currentSite.GetSubwebsForCurrentUser();
            var webcollectionList = webcollection.ToList();
            webcollectionList.Insert(0, currentSite);

            foreach (var web in webcollectionList)
            {
                if (PublishingWeb.IsPublishingWeb(web))
                {
                    var site = new ListItem(web.ServerRelativeUrl);

                    if (_selectedSites != null) site.Selected = _selectedSites.Contains(web.ServerRelativeUrl);

                    sites.Items.Add(site);
                }
            }

            return sites;
        }

        string GetSelectedSitesAsString()
        {
            string selectedSites = "";
            foreach (ListItem item in _sitesCheckBoxList.Items)
            {
                if (item.Selected)
                {
                    selectedSites += item.Value + ";";
                }
            }
            if (selectedSites.Length > 0) selectedSites = selectedSites.Remove(selectedSites.Length - 1);
            return selectedSites;
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            var webPart = WebPartToEdit as EnhancedContentQuery.EnhancedContentQuery;
            if (webPart != null)
            {
                webPart.Sites = GetSelectedSitesAsString();
            }

            return true;
        }

        public override void SyncChanges()
        {
            var webPart = WebPartToEdit as EnhancedContentQuery.EnhancedContentQuery;
            if (webPart != null)
            {
                if (!string.IsNullOrEmpty(webPart.Sites))
                {
                    _selectedSites = webPart.Sites.Split(';').ToList();
                }
                else
                {
                    _selectedSites = new List<string>();
                }
            }
            EnsureChildControls();
        } 
    }
}